// DeviceVideoListActivity.java
package com.xsq.wifi.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.Switch;

import androidx.recyclerview.widget.LinearLayoutManager;

import com.xsq.wifi.R;
import com.xsq.wifi.adapter.DeviceVideoAdapter;
import com.xsq.wifi.callback.Callbacks;
import com.xsq.wifi.databinding.ActivityDeviceVideoListBinding;
import com.xsq.wifi.model.DeviceVideoListModel;
import com.xsq.wifi.utils.PersistentConnection;
import com.xsq.wifi.utils.ToastUtil;
import com.xsq.wifi.utils.WifiListFetcher;
import com.xsq.wifi.view.CustomProgressBar;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class DeviceVideoListActivity extends BaseActivity {

    private static final String TAG = "DeviceVideoListActivity";
    private ActivityDeviceVideoListBinding binding;
    private DeviceVideoAdapter deviceVideoAdapter;
    private List<DeviceVideoListModel> deviceVideoListModels = new ArrayList<>();
    private String deviceIp;
    private String deviceUuid;

    private Handler handler = new Handler(Looper.getMainLooper());
    private Runnable statusPollingRunnable;
    private static final int POLL_INTERVAL_MS = 500;
    private int lastProgress = -1;
    private String lastPlayingVideo = null;
    private boolean isFirstVideo = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityDeviceVideoListBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        deviceIp = getIntent().getStringExtra("device_ip");
        deviceUuid = getIntent().getStringExtra("device_uuid");
//        try {
//            PersistentConnection.getInstance().connect(deviceIp);
//        } catch (IOException e) {
//            throw new RuntimeException(e);
//        }
        initViews();
        binding.backImg.setOnClickListener(v -> finish());
    }

    private void initViews() {
        int lastDashIndex = deviceUuid.lastIndexOf("-");
        String macAddress = deviceUuid.substring(lastDashIndex + 1);
        binding.titleText.setText("BEVERG_"+macAddress.toUpperCase());

        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        binding.recyclerView.setLayoutManager(layoutManager);

        deviceVideoAdapter = new DeviceVideoAdapter(deviceVideoListModels, this);

        deviceVideoAdapter.setOnItemClickListener(path -> {
//            // 手动设置播放视频
//            WifiListFetcher.playvideo(deviceIp, deviceVideoAdapter.getSelectedVideoName(), new Callbacks.ConfigCallback() {
//                @Override
//                public void onSuccess() {
//                    Log.v(TAG, "手动设置播放成功");
//                    // 点击视频项的处理
//                    //getPlayqStatus();
//                }
//                @Override
//                public void onFailure(String error) {
//                    Log.e(TAG, "播放状态设置失败: " + error);
//                }
//            });
        });

       // 设置开始和暂停
        deviceVideoAdapter.setOnPlayStatusClickListener((isplay, callback) -> {
            WifiListFetcher.setPlayStatus(deviceIp, isplay, new Callbacks.ConfigCallback() {
                @Override
                public void onSuccess() {
                    callback.onSuccess(); // 通知Adapter操作成功
                    Log.v(TAG, "操作成功");
                }
                @Override
                public void onFailure(String error) {
                    callback.onFailure(); // 通知Adapter操作失败
                    Log.e(TAG, "操作失败: " + error);
                }
            });
        });

        binding.recyclerView.setAdapter(deviceVideoAdapter);

        // 获取视频列表
        WifiListFetcher.getVideoList(deviceIp, new Callbacks.VideoListCallback() {
            @Override
            public void onSuccess(List<String> videoList) {
                Log.v(TAG,videoList.size()+"------");
                // 获取视频封面
                WifiListFetcher.getVideoThumbnailsBatch(deviceIp, videoList, new Callbacks.VideoImgListBatchCallback() {
                    @Override
                    public void onSuccess(List<DeviceVideoListModel> results) {
                        runOnUiThread(() -> {
                            deviceVideoListModels.clear();
                            deviceVideoListModels.addAll(results);
                            deviceVideoAdapter.notifyDataSetChanged();
                            // 启动轮询
                            startPolling();
                        });
                    }
                    @Override
                    public void onFailure(String error) {
                        Log.e(TAG, "获取视频封面失败: " + error);
                    }
                });
            }
            @Override
            public void onFailure(String error) {
                Log.e(TAG, "获取视频列表失败: " + error);
            }
        });

        //播放上一曲
        binding.playUp.setOnClickListener(v -> {
            WifiListFetcher.setVideoUp(deviceIp, new Callbacks.ConfigCallback() {
                @Override
                public void onSuccess() {
                    Log.v(TAG, "播放上一曲成功");
                }
                @Override
                public void onFailure(String error) {
                    Log.e(TAG, "播放上一曲操作失败: " + error);
                }
            });
        });
        //播放下一曲
        binding.playDown.setOnClickListener(v -> {
            WifiListFetcher.setVideoDown(deviceIp, new Callbacks.ConfigCallback() {
                @Override
                public void onSuccess() {
                    Log.v(TAG, "播放下一曲成功");
                }
                @Override
                public void onFailure(String error) {
                    Log.e(TAG, "播放下一曲操作失败: " + error);
                }
            });
        });
        //播放列表刷新
        binding.playUpdate.setOnClickListener(v -> {
            WifiListFetcher.updateVideoList(deviceIp, new Callbacks.ConfigCallback() {
                @Override
                public void onSuccess() {
                    Log.v(TAG, "刷新列表成功");
                }

                @Override
                public void onFailure(String error) {
                    Log.e(TAG, "刷新列表操作失败: " + error);
                }
            });
        });
        //设置
        binding.setImg.setOnClickListener(v -> {
             showpopwindow();
        });
        //上传文件
        binding.uploadImg.setOnClickListener(v -> {
            Intent intent = new Intent(DeviceVideoListActivity.this, UploadVideoActivity.class);
            intent.putExtra("deviceIp", deviceIp);
            startActivity(intent);
            finish();
        });
    }
    private void showpopwindow(){
        View chooseHeadView = LayoutInflater.from(DeviceVideoListActivity.this).inflate(R.layout.setting_pop, null);
        PopupWindow popupWindow = new PopupWindow(chooseHeadView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        ImageView close_img = (ImageView) chooseHeadView.findViewById(R.id.close_img);

        RelativeLayout jian_liang_rl = (RelativeLayout) chooseHeadView.findViewById(R.id.jian_liang_rl);
        CustomProgressBar customProgressBar = (CustomProgressBar) chooseHeadView.findViewById(R.id.customProgressBar);
        RelativeLayout jia_liang_rl = (RelativeLayout) chooseHeadView.findViewById(R.id.jia_liang_rl);
        jia_liang_rl.setOnClickListener(v -> {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if(customProgressBar.getProgress()==100){
                        ToastUtil.show(DeviceVideoListActivity.this,"已到最大值");
                    }else{
                        WifiListFetcher.setBrightness(deviceIp, (int) (customProgressBar.getProgress()+10), new Callbacks.ConfigCallback() {
                            @Override
                            public void onSuccess() {
                                customProgressBar.setProgress(customProgressBar.getProgress()+10);
                                Log.v("liangdu", "亮度设置成功");
                            }

                            @Override
                            public void onFailure(String error) {
                                Log.e("liangdu", "亮度设置操作失败: " + error);
                            }
                        });
                    }
                }
            });
        });
        jian_liang_rl.setOnClickListener(v -> {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if(customProgressBar.getProgress()==0){
                        ToastUtil.show(DeviceVideoListActivity.this,"已到最小值");
                    }else{
                        WifiListFetcher.setBrightness(deviceIp, (int) (customProgressBar.getProgress()-10), new Callbacks.ConfigCallback() {
                            @Override
                            public void onSuccess() {
                                customProgressBar.setProgress(customProgressBar.getProgress()-10);
                                Log.v("liangdu", "亮度设置成功");
                            }

                            @Override
                            public void onFailure(String error) {
                                Log.e("liangdu", "亮度设置操作失败: " + error);
                            }
                        });
                    }
                }
            });
        });


        RelativeLayout jian_jiao_rl = (RelativeLayout) chooseHeadView.findViewById(R.id.jian_jiao_rl);
        CustomProgressBar customProgressBar1 = (CustomProgressBar) chooseHeadView.findViewById(R.id.customProgressBar1);
        RelativeLayout jia_jiao_rl = (RelativeLayout) chooseHeadView.findViewById(R.id.jia_jiao_rl);

        jia_jiao_rl.setOnClickListener(v -> {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    float currentProgress = customProgressBar1.getProgress();
                    // 计算新角度（确保不超过359）
                    float newAngle = Math.min(currentProgress + 20, 359);

                    if (currentProgress >= 359) {
                        ToastUtil.show(DeviceVideoListActivity.this, "已到最大值");
                        return;
                    }
                    WifiListFetcher.setAngle(deviceIp, (int) newAngle, new Callbacks.ConfigCallback() {
                        @Override
                        public void onSuccess() {
                            // 在UI线程更新进度条
                            runOnUiThread(() -> {
                                customProgressBar1.setProgress(newAngle);
                                Log.v("liangdu", "角度设置成功，新角度: " + newAngle);
                            });
                        }

                        @Override
                        public void onFailure(String error) {
                            runOnUiThread(() -> {
                                Log.e("liangdu", "角度设置操作失败: " + error);
                                ToastUtil.show(DeviceVideoListActivity.this, "设置失败: " + error);
                            });
                        }
                    });
                }
            });
        });
        jian_jiao_rl.setOnClickListener(v -> {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if(customProgressBar1.getProgress()==0){
                        ToastUtil.show(DeviceVideoListActivity.this,"已到最小值");
                    }else{
                        WifiListFetcher.setBrightness(deviceIp, (int) (customProgressBar1.getProgress()-20), new Callbacks.ConfigCallback() {
                            @Override
                            public void onSuccess() {
                                customProgressBar1.setProgress(customProgressBar1.getProgress()-20);
                                Log.v("liangdu", "角度设置成功");
                            }

                            @Override
                            public void onFailure(String error) {
                                Log.e("liangdu", "角度设置操作失败: " + error);
                            }
                        });
                    }
                }
            });
        });

        RelativeLayout jian_yin_rl = (RelativeLayout) chooseHeadView.findViewById(R.id.jian_yin_rl);
        CustomProgressBar customProgressBar2 = (CustomProgressBar) chooseHeadView.findViewById(R.id.customProgressBar2);
        RelativeLayout jia_yin_rl = (RelativeLayout) chooseHeadView.findViewById(R.id.jia_yin_rl);

        jia_yin_rl.setOnClickListener(v -> {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if(customProgressBar2.getProgress()==100){
                        ToastUtil.show(DeviceVideoListActivity.this,"已到最大值");
                    }else{
                        WifiListFetcher.setVolume(deviceIp, (int) (customProgressBar2.getProgress()+10), new Callbacks.ConfigCallback() {
                            @Override
                            public void onSuccess() {
                                customProgressBar2.setProgress(customProgressBar2.getProgress()+10);
                                Log.v("liangdu", "亮度设置成功");
                            }

                            @Override
                            public void onFailure(String error) {
                                Log.e("liangdu", "亮度设置操作失败: " + error);
                            }
                        });
                    }
                }
            });
        });
        jian_yin_rl.setOnClickListener(v -> {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if(customProgressBar2.getProgress()==0){
                        ToastUtil.show(DeviceVideoListActivity.this,"已到最小值");
                    }else{
                        WifiListFetcher.setVolume(deviceIp, (int) (customProgressBar2.getProgress()-10), new Callbacks.ConfigCallback() {
                            @Override
                            public void onSuccess() {
                                customProgressBar2.setProgress(customProgressBar2.getProgress()-10);
                                Log.v("liangdu", "音量设置成功");
                            }

                            @Override
                            public void onFailure(String error) {
                                Log.e("liangdu", "音量设置操作失败: " + error);
                            }
                        });
                    }
                }
            });
        });

        Switch iskaiji_button = (Switch) chooseHeadView.findViewById(R.id.iskaiji_button);
        // 设置点击事件监听器
        iskaiji_button.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    // Switch 被打开时执行的操作
                    Log.v("SwitchState", "开关被打开");
                    WifiListFetcher.setDisplay(deviceIp,"1", new Callbacks.ConfigCallback() {
                        @Override
                        public void onSuccess() {
                            Log.v("liangdu", "开屏设置成功");
                        }

                        @Override
                        public void onFailure(String error) {
                            Log.e("liangdu", "开屏设置操作失败: " + error);
                        }
                    });
                } else {
                    // Switch 被关闭时执行的操作
                    Log.v("SwitchState", "开关被关闭");
                    WifiListFetcher.setDisplay(deviceIp,"0", new Callbacks.ConfigCallback() {
                        @Override
                        public void onSuccess() {
                            Log.v("liangdu", "关屏设置成功");
                        }

                        @Override
                        public void onFailure(String error) {
                            Log.e("liangdu", "关屏设置操作失败: " + error);
                        }
                    });
                }
            }
        });
        LinearLayout shengji_ll = (LinearLayout) chooseHeadView.findViewById(R.id.shengji_ll);
        shengji_ll.setOnClickListener(v -> {

        });
        WifiListFetcher.getWorkStatus(deviceIp, new Callbacks.VideoStatusCallback() {
            @Override
            public void onSuccess(String jsonStr) {
                try {
                    Log.v("statusget",jsonStr);
                    JSONObject jsonObject = new JSONObject(jsonStr);
                    int display = jsonObject.getInt("display");
                    int brightness = jsonObject.getInt("brightness");
                    int angle = jsonObject.getInt("angle");
                    int volume = jsonObject.getInt("brightness");
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            customProgressBar.setMax(100);
                            customProgressBar.setProgress(brightness);

                            customProgressBar1.setMax(359);
                            customProgressBar1.setProgress(angle);

                            customProgressBar2.setMax(100);
                            customProgressBar2.setProgress(volume);

                            if(display==0){
                                iskaiji_button.setChecked(true);
                            }else {
                                iskaiji_button.setChecked(false);
                            }
                        }
                    });
                } catch (JSONException e) {
                    Log.e("statusget", "解析状态失败", e);
                }
                Log.v("statusget", "工作状态获取成功");
            }

            @Override
            public void onFailure(String error) {
                Log.e("statusget", "工作状态操作失败: " + error);
            }
        });
        close_img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
        setBackgroundAlpha(0.5f,popupWindow);
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(false);
        popupWindow.showAtLocation(chooseHeadView, Gravity.BOTTOM,0,0);
    }

    private void setBackgroundAlpha(float bgAlpha,PopupWindow popupWindow) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = bgAlpha;//设置透明度（这是窗体本身的透明度，非背景）
        lp.dimAmount = bgAlpha;//设置灰度
        if (bgAlpha == 1) {
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);//不移除该Flag的话,在有视频的页面上的视频会出现黑屏的bug
        } else {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);//此行代码主要是解决在华为 红米米手机上半透明效果无效的bug
        }
        getWindow().setAttributes(lp);
        //监听弹窗
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                //弹窗关闭  dismiss()时恢复原样
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = 1f;
                getWindow().setAttributes(lp);
            }
        });
    }
    private void startPolling() {
        if (statusPollingRunnable != null) {
            handler.removeCallbacks(statusPollingRunnable);
        }

        statusPollingRunnable = new Runnable() {
            @Override
            public void run() {
                getPlayqStatus();
                Log.v(TAG,deviceVideoAdapter.getSelectedVideoName()+"");
                handler.postDelayed(this, POLL_INTERVAL_MS);
            }
        };
        handler.post(statusPollingRunnable);
    }

    public void getPlayqStatus() {
        WifiListFetcher.getPlayStatus(deviceIp, new Callbacks.VideoStatusCallback() {
            @Override
            public void onSuccess(String jsonStr) {
                try {
                    JSONObject jsonObject = new JSONObject(jsonStr);
                    String status = jsonObject.getString("status");
                    String filename = jsonObject.getString("filename");
                    Log.v("namename",filename);
                    int frames = jsonObject.getInt("frames");
                    int curr_frame = jsonObject.getInt("curr_frame");
                    int progress = (int)((float)curr_frame / frames * 100);
                    progress = Math.max(0, Math.min(progress, 100));
                    Log.v(TAG,progress+"");

                    // 检查是否是新的视频开始播放
                    boolean isNewVideo = !filename.equals(lastPlayingVideo);
                    lastPlayingVideo = filename;

                    // 检查是否播放完成
                    boolean isFinished = progress >= 99 && "playing".equals(status);

                    int finalProgress = progress;
                    runOnUiThread(() -> {
                        if (isNewVideo) {
                            // 新视频开始播放，移动到首位（仅第一次）
                            if (isFirstVideo) {
                                deviceVideoAdapter.setSelectedVideo(filename, true);
                                isFirstVideo = false;
                            } else {
                                deviceVideoAdapter.updateSelectedVideo(filename);
                            }
                        } else if (isFinished) {
                            // 播放完成，自动切换到下一个视频（不置顶）
                            deviceVideoAdapter.selectNextVideo();
                        }

                        // 更新进度
                        if (finalProgress != lastProgress) {
                            lastProgress = finalProgress;
                            deviceVideoAdapter.updateDeviceProgress(filename, finalProgress);
                        }
                    });

                } catch (JSONException e) {
                    Log.e(TAG, "解析播放状态失败", e);
                }
            }
            @Override
            public void onFailure(String error) {
                Log.e(TAG, "获取播放状态失败: " + error);
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        PersistentConnection.getInstance().disconnect();
        // 停止轮询
        if (handler != null && statusPollingRunnable != null) {
            handler.removeCallbacks(statusPollingRunnable);
        }
    }
}